package com.codemes.happylist.modules.transform;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author nscoffee
 */
@Slf4j
public class TransformUtil {

    private TransformUtil(){

    }

    public static List<TransformItem> loadItemList(){
        String content = FileUtil.readString(Objects.requireNonNull(UnitTransformController.class.getResource("/fxml/transform/transform.json")),"UTF-8");
        log.info("content->{}",content);
        JSONArray contentArray = JSONUtil.parseArray(content);
        return contentArray.toList(TransformItem.class);
    }

    public static List<TransformResult> doTransform(String inputValue, TransformUnit sourceUnit, TransformUnit targetUnit, List<TransformUnit> unitList) {
        if(StringUtils.isEmpty(inputValue)){
            log.warn("输入内容为空，不进行任何操作");
            return Collections.emptyList();
        }
        if(!NumberUtil.isNumber(inputValue)){
            log.warn("输入内容不是数字，不进行任何处理，value—>{}",inputValue);
            return Collections.emptyList();
        }
        if(null==sourceUnit){
            log.warn("没有选择原单位，不进行任何处理");
            return Collections.emptyList();
        }
        BigDecimal begin = BigDecimal.ONE;
        for(TransformUnit unit : unitList){
            if(unit.getName().equals(sourceUnit.getName())){
                break;
            }
            BigDecimal radixUp = unit.getRadixUp();
            begin = begin.multiply(radixUp);
        }
        BigDecimal inputNum = new BigDecimal(inputValue);
        log.info("begin->{} beigin->{}",inputNum,begin);
        begin = inputNum.divide(begin,10,RoundingMode.HALF_DOWN);

        List<TransformResult> results = new ArrayList<>();

        BigDecimal nextRadixUp = null;
        for(TransformUnit unit : unitList){
            log.info("unit->{} up->{} begin->{}",unit.getName(),unit.getRadixUp(),begin);
            if(nextRadixUp!=null){
                begin = begin.multiply(nextRadixUp);
            }
            nextRadixUp = unit.getRadixUp();

            TransformResult result = new TransformResult();
            result.setResult(begin.stripTrailingZeros().toPlainString());
            result.setTargetUnit(unit);
            results.add(result);
        }

        if(targetUnit!=null){
            results.stream().filter(re -> {
                return re.getTargetUnit().getName().equals(targetUnit.getName());
            }).findFirst().ifPresentOrElse(e -> {
                results.clear();
                results.add(e);
            } ,null);
        }
        return results;
    }
}
